package com.grao.waterschool.human.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.DefaultResponseErrorHandler;

import java.io.IOException;

@Slf4j
@ControllerAdvice
public class CustomErrorHandler extends DefaultResponseErrorHandler {

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        if (response.getRawStatusCode() != HttpStatus.UNAUTHORIZED.value()) {
            super.handleError(response);
        } else {
            // 忽略401 Unauthorized状态，仅记录日志
            log.warn("您收到 HTTP 401 未经授权的响应： {}", response.getStatusText());
        }
    }

    @ResponseBody
    @ExceptionHandler(value = {Exception.class})
    public ResponseEntity<Object> handleAllUncaughtExceptions(Exception ex) {

        return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
